﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HumanResourceManagementSystem.DataAccessLayer;
using System.Data;
using System.Xml;
using System.Configuration;

namespace HumanResourceManagementSystem.BusinessLogicLayer
{
    class ProjectManagement
    {
        public static DataTable getProjets()
        {
            return SQL.getProjects();
        }

        public static bool writeToXml(string projID, string projName, DateTime startDate, DateTime endDate, string clientID)
        {
            bool result = true;
            XmlDocument xmlDoc = new XmlDocument();
            try
            {
                xmlDoc.Load(ConfigurationManager.AppSettings["Path"] + "\\Projects.xml");
            }
            catch
            {
                XmlElement rootNode = xmlDoc.CreateElement("Projects");
                xmlDoc.AppendChild(rootNode);
            }
            bool projectExisted = false;
            XmlNode node = xmlDoc.DocumentElement;
            foreach (XmlNode node1 in node.ChildNodes)
            {
                if (node1.Name == "Project" && node1.Attributes["ID"].Value == projID)
                {
                    projectExisted = true;
                    foreach (XmlNode node2 in node1.ChildNodes)
                    {
                        if (node2.Name == "ProjName") node2.InnerText = projName;
                        else if (node2.Name == "StartDate") node2.InnerText = startDate.ToShortDateString();
                        else if (node2.Name == "EndDate") node2.InnerText = endDate.ToShortDateString();
                        else if (node2.Name == "ClientID") node2.InnerText = clientID;
                    }
                }
            }
                
            if (!projectExisted)
            {
                XmlElement parentNode = xmlDoc.CreateElement("Project");
                parentNode.SetAttribute("ID", projID);
                xmlDoc.DocumentElement.PrependChild(parentNode);

                XmlElement nameNode = xmlDoc.CreateElement("ProjName");
                XmlElement startDateNode = xmlDoc.CreateElement("StartDate");
                XmlElement endDateNode = xmlDoc.CreateElement("EndDate");
                parentNode.AppendChild(nameNode);
                parentNode.AppendChild(startDateNode);
                parentNode.AppendChild(endDateNode);
                nameNode.InnerText = projName;
                startDateNode.InnerText = startDate.ToShortDateString();
                endDateNode.InnerText = endDate.ToShortDateString();
            }
            
            xmlDoc.Save(ConfigurationManager.AppSettings["Path"] + "\\Projects.xml");
            return result;
        }
    }
}
